package com.example.redis.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.example.redis.domain.UserDTO;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.awt.image.PackedColorModel;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * JacksonUtils工具类
 *
 * @Author guoyb
 * @Date 2020/1/15  14:38
 */
@Slf4j
public class JacksonUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private JacksonUtils() {

    }

    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     * javaBean、列表数组转换为json字符串
     */
    public static String obj2json(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("异常信息:{}", e.getMessage());
        }
        return null;
    }

    /**
     * javaBean、列表数组转换为json字符串,忽略空值
     */
    public static String obj2jsonIgnoreNull(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("异常信息:{}", e.getMessage());
        }
        return null;
    }

    /**
     * json 转JavaBean
     */
    public static <T> T json2pojo(String jsonString, Class<T> clazz) throws IOException {
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return objectMapper.readValue(jsonString, clazz);
    }

    /**
     * jsonArray转List<T>
     *
     * @param jsonArrayStr
     * @return
     */
    public static <T> List<T> jsonArrayToList(String jsonArrayStr, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        if (StrUtil.isBlank(jsonArrayStr)) {
            return list;
        }
        try {
            // list = JSONObject.parseArray(jsonArrayStr, String.class);
            list = JSONUtil.toList(JSONUtil.parseArray(jsonArrayStr), clazz);
        } catch (Exception e) {
            log.error("jsonArrayToList:异常信息:{}", e.getMessage());
        }
        return list;
    }

    // public static void main(String[] args) {
    //     List<UserDTO> userDTOS = jsonArrayToList("[{\"id\":2,\"username\":\"demoData2\",\"age\":2},{\"id\":1,\"username\":\"demoData\",\"age\":1}]", UserDTO.class);
    //     System.out.println("userDTOS = " + userDTOS);
    // }
}
